﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;

namespace Sys.Excel
{
    internal static class Utils
    {
        public static IEnumerable<IEnumerable<T>> ToPager<T>(this IEnumerable<T> target, int pageSize = 100)
        {
            if (target == null)
            {
                yield break;
            }

            var index = 0;
            var size = Math.Max(pageSize, 1);
            var list = target as IReadOnlyList<T> ?? new List<T>(target);
            var count = list.Count;

            while (true)
            {
                yield return GetPage(list, count, index++, size);

                if (checked(index * size) >= count)
                {
                    yield break;
                }
            }

            IEnumerable<T> GetPage(IReadOnlyList<T> list_t, int count_t, int p_index, int p_size)
            {
                var max = Math.Min(checked((p_index + 1) * p_size), count_t);

                for (int i = checked(p_index * p_size); i < max; i++)
                {
                    yield return list_t[i];
                }
            }
        }

        public static object GetValue(DataRow row, string field)
        {
            if (row == null)
            {
                return null;
            }

            if (!row.Table.Columns.Contains(field))
            {
                return null;
            }

            return row[field];
        }

        public static object GetValue(IDictionary<string, object> dict_g, string field)
        {
            if (dict_g == null)
            {
                return null;
            }

            if (!dict_g.TryGetValue(field, out object val))
            {
                return null;
            }

            return val;
        }

        public static object GetValue(IDictionary dict, string field)
        {
            if (dict == null)
            {
                return null;
            }

            if (!dict.Contains(field))
            {
                return null;
            }

            return dict[field];
        }
    }
}